999. 可以被一步捕获的棋子数
为保证权益,题目请参考 999. 可以被一步捕获的棋子数(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std;
//999
class Solution {
public:
int numRookCaptures(vector<vector<char>> &board) {
int x = 0;
int y = 0;
for (int i = 0; i < board.size(); ++i) {
bool flag = false;
for (int j = 0; j < board[0].size(); ++j) {
if (board[i][j] == 'R') {
x = i;
y = j;
flag = true;
break;
}
}
if (flag) {
break;
}
}
int ans = 0;
//up
for (int i = x - 1; i >= 0; --i) {
if (board[i][y] == 'B') {
break;
} else if (board[i][y] == 'p') {
ans++;
break;
}
}
//down
for (int i = x + 1; i < board.size(); ++i) {
if (board[i][y] == 'B') {
break;
} else if (board[i][y] == 'p') {
ans++;
break;
}
}
//left
for (int i = y - 1; i >= 0; --i) {
if (board[x][i] == 'B') {
break;
} else if (board[x][i] == 'p') {
ans++;
break;
}
}
//down
for (int i = y + 1; i < board[0].size(); ++i) {
if (board[x][i] == 'B') {
break;
} else if (board[x][i] == 'p') {
ans++;
break;
}
}
return ans;
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Python
python
from typing import List
class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
white_car_x = -1
white_car_y = -1
for row_idx, row in enumerate(board):
for col_idx, x in enumerate(row):
if x == "R":
white_car_x = row_idx
white_car_y = col_idx
ans = 0
# up
for d in range(1, 8):
if white_car_x - d < 0:
break
if board[white_car_x - d][white_car_y] == "B":
break
elif board[white_car_x - d][white_car_y] == "p":
ans += 1
break
# down
for d in range(1, 8):
if white_car_x + d >= 8:
break
if board[white_car_x + d][white_car_y] == "B":
break
elif board[white_car_x + d][white_car_y] == "p":
ans += 1
break
# left
for d in range(1, 8):
if white_car_y - d < 0:
break
if board[white_car_x][white_car_y - d] == "B":
break
elif board[white_car_x][white_car_y - d] == "p":
ans += 1
break
# right
for d in range(1, 8):
if white_car_y + d >= 8:
break
if board[white_car_x][white_car_y + d] == "B":
break
elif board[white_car_x][white_car_y + d] == "p":
ans += 1
break
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56